<template>
  <content-box :title="`当班${statusList[4].label}时长明细`" :btn-label="`当班${statusList[4].label}原因明细`" @toDetail="showDetail" :loading="loading" :disable="!chartData.length">
    <div class="chart" ref="chart" id="chart" style="height: 300px"/>
    <table-basic type="alarm" :label="`${statusList[4].label}时长`" ref="alarmDetail"/>
  </content-box>
</template>

<script>
import contentBox from './content-box'
import TableBasic from './table-basic'
import { addListener } from 'resize-detector'
import echarts from 'echarts'
import chart from './chart-option'
import { getAlarmChart } from 'src/boot/status-monitor/status-overview'
import { mapGetters } from 'vuex'
import _ from 'lodash'
export default {
  name: 'alarm-rate',
  components: {
    contentBox,
    TableBasic
  },
  computed: {
    ...mapGetters(['statusList'])
  },
  data () {
    return {
      title: '当班报警时长明细',
      loading: false,
      chart: null,
      chartData: [],
      params: {}
    }
  },
  mounted () {
    addListener(this.$refs.chart, this.$utils.debounce(() => {
      if (this.$route.name !== 'statusOverview') {
        return
      }
      if (this.chart === null) {
        this.chart = echarts.init(this.$refs.chart)
      } else {
        this.chart.resize()
        this.setOption()
      }
    }, 100))
  },
  methods: {
    showDetail () {
      this.$refs.alarmDetail.showDetail(this.params)
    },
    clearData () {
      this.chartData = []
      this.setOption()
    },
    getAlarmChart (time, workshopId, lineId) {
      this.loading = true
      let params = {
        ...time
      }
      lineId !== 'all' && (params['lineId'] = lineId)
      lineId === 'all' && (params['workshopId'] = workshopId)
      this.params = params
      getAlarmChart(params).then(res => {
        let chartData = []
        if (res.length) {
          chartData = res.map(item => {
            const shiftTime = this.$utils.label(item.shiftTime, 0)
            let alarmTime = Number(this.$utils.label(item.alarmTime, 0) / shiftTime * 100)
            alarmTime > 100 && (alarmTime = 100)
            return {
              name: item.deviceName ? `${item.deviceName || ''}(${item.deviceId})` : this.$utils.label(item.deviceId),
              value: this.$utils.label(item.alarmTime, 0),
              percent: shiftTime ? alarmTime.toFixed(2) : 0.00
            }
          })
        }
        this.chartData = _.sortBy(chartData, ['value']).reverse()
        this.setOption(this.chartData)
      }).finally(() => {
        this.loading = false
      })
    },
    setOption (data = this.chartData) {
      if (this.chart === null) {
        this.chart = echarts.init(this.$refs.chart)
      }
      const option = chart.getRateBar(data, ['#F7B82D', '#FF8559'], document.getElementById('chart'))
      this.chart.setOption(option)
    }
  }
}
</script>

<style scoped>

</style>
